package name.sakanacatcher.controller;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import name.sakanacatcher.entity.Com;
import name.sakanacatcher.entity.User;
import name.sakanacatcher.service.AuthService;
import name.sakanacatcher.service.ComService;
import name.sakanacatcher.service.RoleService;
import name.sakanacatcher.service.UserService;
import name.sakanacatcher.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/com")
public class ComController {

    @Autowired
    ComService comService;

    @Autowired
    RoleService roleService;

    @Autowired
    UserService userService;

    @Autowired
    ResultUtil resultUtil;

    @Autowired
    AuthService authService;

    @GetMapping("/detail")
    public Map<String,Object> getComId(@RequestParam int id){
        return resultUtil.successResult("send Success",Map.of("items", comService.getComRepository().getById(id)));
    }
    @GetMapping("/detail/auth")
    public Map<String,Object> getComByAuth(){
        String reqUsername = SecurityContextHolder.getContext().getAuthentication().getName();
        User reqUser = userService.getUserRepository().getByUsername(reqUsername);
        if (authService.isCEO(reqUser) || authService.isAdmin(reqUser)){
            return resultUtil.successResult("send Success",Map.of("items", reqUser.getCom()));
        }
        else {
            return resultUtil.customResult(401,"你没有权限访问");
        }
    }
    @PostMapping("/update")
    public Map<String,Object> updateCom(@RequestBody Map<String,Object> data){
        String reqUsername = SecurityContextHolder.getContext().getAuthentication().getName();
        User reqUser = userService.getUserRepository().getByUsername(reqUsername);
        if ((authService.isCEO(reqUser) || authService.isAdmin(reqUser)) && comService.updateCom(data)){
            return resultUtil.successResult("send Success");
        }
        else {
            return resultUtil.customResult(401,"你没有权限修改");
        }
    }
    @GetMapping("/check/name/beforeUpdate")
    public Map<String,Object> getComByAuth(@RequestParam("name") String name, @RequestParam("id") int id){
        return resultUtil.successResult("get Success", comService.getComRepository().existsComByName(name) && !comService.getComRepository().getById(id).getName().equals(name));
    }

    @GetMapping("/list")
    public Map<String, Object> getTable(@RequestParam(name = "page", required = true) int page,
                                        @RequestParam(name = "limit", required = true) int limit,
                                        @RequestParam(name = "type", required = false) String type,
                                        @RequestParam(name = "title", required = false) String title,
                                        @RequestParam(name = "status", required = false) boolean status) throws JsonProcessingException {
        List<Com> table = comService.getComTable();
        System.out.println(table);
        // 条件筛选
        table =  table.stream().filter(
                item ->{
                    if(item.getId() == 0){
                        return false;
                    }
                    ObjectMapper mapper = new ObjectMapper();
                    try {
                        String json=mapper.writeValueAsString(item); //将对象转换成json
                        JSONObject m = JSONObject.parseObject(json);
                        boolean flag = true;
                        if (title != null && !title.equals("")) {
                            flag = false;
                            if (type != null && !type.equals("")) {
                                if(type.equals("id"))
                                    flag = m.get("id").equals(Integer.parseInt(title));
                                else
                                    flag = ((String)m.get(type)).contains(title);
                            } else {
                                flag = ((String)m.get("name")).contains(title) ;
                            }
                        }
                        return flag;
                    } catch (JsonProcessingException e) {
                        e.printStackTrace();
                        return false;
                    }
                }
        ).collect(Collectors.toList());
        int total = table.size();
        int totalPage = (int)Math.ceil(total / (double)limit);
        if(page <= totalPage && page >= 1){
            if(page * limit > total){
                table = table.subList((page - 1)*limit,total);
            }
            else {
                table = table.subList((page - 1)*limit,page * limit);
            }
        }
        return resultUtil.successResult("Get Success", Map.of("items", table, "total", total));
    }

}
